import { createSlice } from "@reduxjs/toolkit";
// import { loginAPI, getProfileAPI } from "@/apis/user";
import { loginAPI } from "@/apis/user";
import { getToken, setToken, clearToken } from "@/utils/token";
const userStore = createSlice({
    name: "user",
    initialState: {
        token: getToken() || "",
        userInfo: {},
        isAuthenticated: false,
    },
    reducers: {
        setUserToken(state, action) {
            state.token = action.payload;
            // 存入本地
            setToken(state.token);
            state.isAuthenticated = true;
        },
        setUserInfo(state, action) {
            state.userInfo = action.payload;
        },
        clearUserInfo(state) {
            state.token = "";
            state.userInfo = {};
            clearToken();
            state.isAuthenticated = false;
        },
    },
});

const { setUserInfo, setUserToken, clearUserInfo } = userStore.actions;

const userReducer = userStore.reducer;

const fetchLogin = (loginFrom) => {
    return async(dispatch) => {
        const res = await loginAPI(loginFrom);
        dispatch(setUserToken(res.data.access_token));
        console.log("setUserToken==>", res.data);
        dispatch(setUserInfo(res.data.userInfo));
    };
};

export { fetchLogin, clearUserInfo };
export default userReducer;